﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SysContext;
using DataAccessLayer;
using System.Windows.Forms;

namespace Business_Logic_Layer
{
    public class BUSS
    {   
   
        TimeRuleTable Timetable = new TimeRuleTable();
        UserTable User = new UserTable();
        CategoriesTable Categorie = new CategoriesTable();
        TransactionsTable TransTable = new TransactionsTable();
        TransactionReminderTable ReminderTable = new TransactionReminderTable();
        AccountsTable Accounts = new AccountsTable();

       /// <summary>
       /// Kiểm tra đăng nhập
       /// </summary>
       /// <param name="name"></param>
       /// <param name="pass"></param>
        /// <returns>Return 1 or 0</returns>
        public int CountUser(string name,string pass)
        {
            if (User.RowcountUser(name, pass) > 0)
                return 1;
            else
                return 0;
        }    
        /// <summary>
        /// Lấy Id User
        /// </summary>
        /// <returns>Return IdUser</returns>
        public int GetIdUser()
        {
            return (int)User.GetID();
       }
        /// <summary>
        /// Contructor lấy Id User
        /// </summary>
        /// <param name="name"></param>
        /// <returns>IdUser</returns>
        public int GetIdUser(string name)
        {
            return (int)User.GetID(name);
        }
        /// <summary>
        /// Lấy Id danh mục
        /// </summary>
        /// <param name="name"></param>
        /// <returns>IdCategory</returns>
        public int GetIdCategory(string name)
        {
            return (int)Categorie.GetIdCategory(name);
        }
        /// <summary>
        /// Lấy Id account
        /// </summary>
        /// <param name="IdUser"></param>
        /// <param name="Type"></param>
        /// <returns>IdAccount</returns>
        public int GetIdAccount(int IdUser, string Type)
        {
            return (int)Accounts.GetAccountId(IdUser, Type);
        }
        /// <summary>
        /// Kiểm tra số tiền nhập không là kiểu chữ
        /// </summary>
        /// <param name="pValue"></param>
        /// <returns>true or false</returns>
        public bool IsNumber(string pValue)
        {
            foreach (Char c in pValue)
            {
                if (!Char.IsDigit(c))
                    return false;
            }
            return true;
        }
        /// <summary>
        /// Insert dữ liệu vào bảng Timerule
        /// </summary>
        /// <param name="StartDate"></param>
        /// <param name="EndDate"></param>
        /// <param name="Repeadmode"></param>
        /// <param name="RepeadValues"></param>
        /// <param name="RepeadSeed"></param>
        public void InsertTimerule(string StartDate, string EndDate, string Repeadmode, string RepeadValues, int RepeadSeed)
        {
            Timetable.InsertTimeRules(StartDate, EndDate, Repeadmode, RepeadValues, RepeadSeed);
        }
        /// <summary>
        /// Lấy id TimeRule
        /// </summary>
        /// <returns>IdTime</returns>
        public double GetIDTimer()
        {
            return Timetable.GetIDTimer();
        }
        /// <summary>
        /// Insert dữ liệu vào bảng TransactionReminder
        /// </summary>
        /// <param name="AccountID"></param>
        /// <param name="Payment"></param>
        /// <param name="Deposit"></param>
        /// <param name="CategoryID"></param>
        /// <param name="Description"></param>
        /// <param name="AutoCommit"></param>
        /// <param name="TimeRuleid"></param>
        public void InsertTransReminder(int AccountID, double Payment, double Deposit, int CategoryID, string Description, int AutoCommit, int TimeRuleid)
        {
            DateTime Time = GetDatetime(TimeRuleid);
            ReminderTable.InsertTransReminder(AccountID, Payment, Deposit, CategoryID, Description, AutoCommit, TimeRuleid, Time.ToShortDateString());
        }
        /// <summary>
        /// Insert dữ liệu vào bảng Account
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="Type"></param>
        /// <param name="Currency"></param>
        /// <param name="Amount"></param>       
        public void InserAccount(int UserID, string Type, string Currency, double Amount)
        {
            Accounts.InsertAccount(UserID, Type, Currency, Amount);
        }
        
        /// <summary>
        /// Insert dữ liệu vào bảng User
        /// </summary>
        /// <param name="Username"></param>
        /// <param name="Password"></param>
        /// <param name="Mail"></param>
        public void InsertUser(string Username, string Password, string Mail)
        {
            User.InsertUser(Username, Password, Mail);
        }

         /// <summary>
         /// Lấy tất cả các dữ liệu trong bảng Category
         /// </summary>
         /// <returns></returns>      
        public List<Category> Categories()
        {
            return Categorie.Category();
        }

        /// <summary>
        /// Lấy dữ liệu trong bảng TransactionReminder
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="AccountType"></param>
        /// <returns></returns>
        public Array TransReminder(int UserID, string AccountType)
        {           
            return ReminderTable.TransReminder(UserID, AccountType);
        }

        /// <summary>
        /// Insert dữ liệu vào bảng Transactions
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="AccountType"></param>
        /// <param name="pay"></param>
        /// <param name="Tienthu"></param>
        /// <param name="Thoigan"></param>
        /// <param name="CategoriesId"></param>
        /// <param name="Lydo"></param>
        /// <param name="total"></param>
        public void InsertTransation(int UserID, string AccountType, double pay, int Tienthu, DateTime Thoigan, int CategoriesId, string Lydo, Double total)
        {
            TransTable.InsertTransation(UserID, AccountType, pay, Tienthu, Thoigan, CategoriesId, Lydo, total);
        }
        /// <summary>
        /// Lấy dữ liệu cột name trong bảng Category
        /// </summary>
        /// <returns>name</returns>
        public Array SelectName()
        {
            return Categorie.SelectName();
        }

        /// <summary>
        /// Lấy dữ liệu trong bảng Transactions
        /// </summary>
        /// <param name="IdUser"></param>
        /// <param name="Type"></param>
        /// <returns></returns>
        public Array SelectTrans(int IdUser, string Type)
        {
            return TransTable.SelectTrans(IdUser, Type);
        }
       
        public void CountOccurredDate(int UserID, string AccountType,DateTime Time)
        {
            int i = 1;
            int Repeatseed = 1;
            DateTime Date = TransTable.GetOccurredDate(UserID, AccountType);  // thoi gian cuoi cung cua giao dich trans          
            while (Date <= Time)  // lay now.
            {
                foreach (var Reminder in ReminderTable.TransReminderAuto(UserID, AccountType, Date).ToList())  // kiem tra dieu kiem start End date
                {
                    string RepeatMode;                   
                    Repeatseed = (int)Timetable.GetRepeatseed(Reminder.TimeRuleId);
                    RepeatMode = Timetable.GetRepeatMode(Reminder.TimeRuleId);
                    if (RepeatMode == "Month")
                    {
                        if (Reminder.LastOccurance == Date)  // Kiem tra ngay Up
                        {
                            if (Reminder.AutoCommit == 1)
                            {
                                if (Reminder.Payment - Reminder.Deposit > 0)
                                {
                                    InsertTransation(UserID, AccountType, (int)Reminder.Payment, (int)Reminder.Deposit, DateTime.Parse(Date.ToShortDateString()), (int)Reminder.CategoryId, Reminder.Description, Reminder.Payment - Reminder.Deposit);
                                }
                                else
                                    InsertTransation(UserID, AccountType, (int)Reminder.Payment, (int)Reminder.Deposit, DateTime.Parse(Date.ToShortDateString()), (int)Reminder.CategoryId, Reminder.Description, Reminder.Deposit - Reminder.Payment);
                            }                           
                        }
                        if (Reminder.Payment - Reminder.Deposit > 0)
                        {
                            InsertTransation(UserID, AccountType, (int)Reminder.Payment, (int)Reminder.Deposit, DateTime.Parse(Date.ToShortDateString()), (int)Reminder.CategoryId, Reminder.Description, Reminder.Payment - Reminder.Deposit);
                        }
                        else
                            InsertTransation(UserID, AccountType, (int)Reminder.Payment, (int)Reminder.Deposit, DateTime.Parse(Date.ToShortDateString()), (int)Reminder.CategoryId, Reminder.Description, Reminder.Deposit - Reminder.Payment);
                        ReminderTable.UpdateTransReminderAuto(Reminder.Id, UpdateGetLastOccurance(UserID, AccountType, Reminder.TimeRuleId, Date).ToString());
                    }

                    else
                    {
                        if (Reminder.LastOccurance == Date)// kiem tra dieu kien cach ngay 
                        {
                            if (Reminder.AutoCommit == 1)
                            {
                                 DialogResult result = MessageBox.Show("Co mot giao dich ","YN", MessageBoxButtons.YesNo);

                                 if (result == DialogResult.Yes)
                                 {
                                     if (Reminder.Payment - Reminder.Deposit > 0)
                                     {
                                         InsertTransation(UserID, AccountType, (int)Reminder.Payment, (int)Reminder.Deposit, DateTime.Parse(Date.ToShortDateString()), (int)Reminder.CategoryId, Reminder.Description, Reminder.Payment - Reminder.Deposit);
                                     }
                                     else
                                         InsertTransation(UserID, AccountType, (int)Reminder.Payment, (int)Reminder.Deposit, DateTime.Parse(Date.ToShortDateString()), (int)Reminder.CategoryId, Reminder.Description, Reminder.Deposit - Reminder.Payment);
                                 }                                
                            }
                            if (Reminder.Payment - Reminder.Deposit > 0)
                            {
                                InsertTransation(UserID, AccountType, (int)Reminder.Payment, (int)Reminder.Deposit, DateTime.Parse(Date.ToShortDateString()), (int)Reminder.CategoryId, Reminder.Description, Reminder.Payment - Reminder.Deposit);
                            }
                            else
                                InsertTransation(UserID, AccountType, (int)Reminder.Payment, (int)Reminder.Deposit, DateTime.Parse(Date.ToShortDateString()), (int)Reminder.CategoryId, Reminder.Description, Reminder.Deposit - Reminder.Payment);
                            ReminderTable.UpdateTransReminderAuto(Reminder.Id, Date.AddDays(Repeatseed).ToShortDateString());
                        }
                    }
                }
                Date = Date.AddDays(i);
            }
        }
        public List<User> SelectUserAll()
        {
            return User.SelectUserAll();
        }
        public DateTime GetDatetime( double TimeRuleId)
        {
            if (Timetable.GetRepeatMode(TimeRuleId) == "Date")
                return DateTime.Now;
            else
            {
                int i = 0;
                int day = 0;
                string str;
                int Date = 0;
                int Month, years;
                string RepeatValues = Timetable.GetRepeatValues(TimeRuleId);
                string[] strSplit = RepeatValues.Split(',');
                DateTime Time = Timetable.GetStartDate(TimeRuleId);
                DateTime Now = DateTime.Today.Date; //Get Date now
                day = (int)Now.Day;
                while (i < strSplit.Length)
                {
                    Date = int.Parse(strSplit[i]);
                    if (Date > day)
                    {
                        Month = Time.Month;
                        years = Time.Year;
                        str = "" + Month + "/" + Date + "/" + years + "";
                        return DateTime.Parse(str);
                    }
                    i++;
                }
                Date = int.Parse(strSplit[0]);
                Month = (int)Time.AddMonths(1).Month;
                if (Month < Now.Month)
                {
                    years = Time.AddYears(1).Year;
                }
                else
                    years = Time.Year;

                str = "" + Month + "/" + Date + "/" + years + "";
                return DateTime.Parse(str);
            }
        }

        public DateTime UpdateGetLastOccurance(int UserID, string AccountType, double TimeRuleId, DateTime Timers)
        {
            int i = 0;
            int Date = 0;
            int day = 0;
            int Month, years;
            string str;

            DateTime Now = DateTime.Today.Date; //Get Date now
            day = (int)Timers.Day;
            string RepeatValues = Timetable.GetRepeatValues(TimeRuleId);
            string[] strSplit = RepeatValues.Split(',');
            while (i < strSplit.Length)
            {
                Date = int.Parse(strSplit[i]);
                if (Date > day)
                {
                    Month = Timers.Month;
                    years = Timers.Year;
                    str = "" + Month + "/" + Date + "/" + years + "";
                    return DateTime.Parse(str);   
                }
                i++;
            }
            Date = int.Parse(strSplit[0]);
            Month = (int)Timers.AddMonths(1).Month;
            if (Month < Now.Month)
            {
                years = Timers.AddYears(1).Year;
            }
            else
                years = Timers.Year;

            str = "" + Month + "/" + Date + "/" + years + "";
            return DateTime.Parse(str);   
        }

        public Array SelectTransViewMonth(int UserId, string AccountType, string input)
        {
            return TransTable.SelectTransViewMonth(UserId, AccountType, input);
        }

        public Array SelectTransViewCategory(int UserId, string AccountType, string category, string year)
        {
            return TransTable.SelectTransViewCategory(UserId, AccountType, category, year);

        }
        public double? Balance(int UserId, string AccountType)
        {
            return TransTable.Balance(UserId, AccountType);
        }

        public Array GetReminder(int UserId)
        {
            return ReminderTable.GetReminder(UserId);

        }

    }
}
